# coding = <utf-8>

import re 
from time import sleep
import serial as serial_module
import serial.tools.list_ports as port_list

class MySerial:
    def __init__(self,tx_queue = None, rx_queue = None):
        self.serial_port = None
        self.serial_status = False
        self.send_finish_command = None
        self.receive_command = None
        self.tx_queue = tx_queue
        self.rx_queue = rx_queue
    def mainloop(self):
        while True:
            if self.read_from_serial_port() is not None:
                if self.rx_queue is not None:
                    self.rx_queue.put(self.read_from_serial_port())
            sleep(0.01)
    def get_serial_ports(self):
        ports = [port.description for port in port_list.comports()]
        return ports
    def open_serial_port(self, port_name, baud_rate, bytesize, parity, stopbits, send_finish_command = None, receive_command = None):
        try:
            port = re.findall(r'COM\d+', port_name)[0]
            self.serial_port = serial_module.Serial(port, baud_rate, bytesize, parity, stopbits)
            self.send_finish_command = send_finish_command
            self.receive_command = receive_command
            self.serial_status = True
            return True
        except:
            return False
    def close_serial_port(self):
        if self.serial_port is not None:
            self.serial_port.flush()
            self.serial_port.close()
            self.serial_port = None
            self.serial_status = False
            return True
        else:
            return False
    def send_to_serial_port(self, data):
        if self.serial_port is not None:
            self.serial_port.write(data)
            if self.send_finish_command is not None:
                self.send_finish_command()
            return True
        else:
            return False
    def read_from_serial_port(self):
        if self.serial_port is not None:
            if self.serial_port.in_waiting > 0:
                data = self.serial_port.read(self.serial_port.in_waiting)
                return data
            else:
                return None
        else:
            return None
    def get_serial_status(self):
        return self.serial_status

def send_flg():
    print("发送完成")

# # 测试代码  
# rs485 = MySerial()  
# dev = rs485.get_serial_ports()  

# if dev:  
#     print("Available Serial Ports:")  
#     for port in dev:  
#         print(f"  {port}")  

#     # 假设选择第一个串口  
#     if rs485.open_serial_port(dev[0], 19200, 8, 'N', 1,send_flg):  
#         print("串口打开成功！")
#         # 发送数据
#         str_data = "hello world"
#         rs485.send_to_serial_port(str_data.encode('utf-8'))
#         # 接收数据
#         # try:  
#         #     for i in range(1000):  
#         #         data = rs485.read_from_serial_port()  
#         #         if data is not None:  
#         #             hex_str = ' '.join([f"{byte:02X}" for byte in data])
#         #             print(f"接收到的数据: {hex_str}")  
#         #         else:  
#         #             pass
#         #         time.sleep(0.1) 
            
#         # except Exception as e:  
#         #     print(f"发生错误: {e}")  
#         # finally:  
#         #     rs485.close_serial_port()  
#         #     print("串口已关闭！")  
# else:  
#     print("没有找到可用的串口！")

        
















